//
//  OAuthViewController.swift
//  新浪微博
//
//  Created by MBP on 16/5/14.
//  Copyright © 2016年 MBP. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()

    override func loadView() {
        view = webView
        
        //设置导航栏
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(OAuthViewController.clickCloseButton))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(OAuthViewController.clickAutoFillButton))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置背景色
        view.backgroundColor = UIColor.whiteColor()
        
        //加载授权 URL
        webView.loadRequest(NSURLRequest(URL: PNNetworkTool.sharedTools.OAuthURL))
        
        //设置代理, 用代理接受网络数据
        webView.delegate = self
    }
    
    //取消按钮点击
    @objc private func clickCloseButton() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充按钮点击
    @objc private func clickAutoFillButton() {
        let js = "document.getElementById('userId').value='18635378140';" +
        "document.getElementById('passwd').value='woaifr1390353509';"
        
        //执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }

}

//webView 代理方法
extension OAuthViewController: UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //判断是否包含回调地址, 不包含则继续 ()
        if let urlString = request.URL?.absoluteString where !urlString.hasPrefix(PNNetworkTool.sharedTools.redirectUri) {
            return true
        }
        //判断URL中 是否包含 "code="
        guard let query = request.URL?.query where query.hasPrefix("code=") else {
            print("取消授权")
            dismissViewControllerAnimated(true, completion: nil)
            return false
        }
        //获得请求码
        let code = query.substringFromIndex("code=".endIndex)
        print("请求码: \(code)")
        
        //将请求码发给服务器获取token
        PNNetworkTool.sharedTools.getAccessToken(code) { (result) -> () in
            guard let result = result else {
                print("网络有问题")
                return
            }
            print(result)
            //创建用户账户
            UserAccount.sharedUserAccount.updateUserAccount(result)
            
            //登录成功, 通知代理工作
            NSNotificationCenter.defaultCenter().postNotificationName(PNWeiboLoginSuccessedNotification, object: nil)
            // 2> 关闭视图控制器
            self.clickCloseButton()
        }
        
        return false
    }
}
